package org.example.judge_common.util;



import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;

public class MyUtils {

    private static Random random = new Random();
    private static String[] types = {"jpg","png","jpeg"};
    /**
     * 判断文件格式是否为图片
     * @param type
     * @return
     */
    public static boolean isImage(String type) {

        for (String s : types) {
            if(s.equals(type))return true;
        }
        return false;
    }
    /**
     * 将字段名转换为数据库字段名 ，驼峰转换为下划线的命名方式
     *
     * @param field
     * @return
     */
    public static String setFieldName(String field) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < field.length(); i++) {
            char c = field.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                str.append('_');
                c = (char) (c - 'A' + 'a');
            }
            str.append(c);
        }
        return str.toString();
    }

    // 判断字符串是否为空
    public static boolean isEmpty(String s) {
        return s == null || "".equals(s);
    }

    public static boolean isNotEmpty(String field) {
        return !isEmpty(field);
    }


    public static String getIp(String ip){
        String result = "未知";
        try {
            URL url = new URL("http://whois.pconline.com.cn/ip.jsp?ip="+ip);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setConnectTimeout(5000);// 设置连接主机超时（单位：毫秒）
            httpURLConnection.setReadTimeout(5000);// 设置从主机读取数据超时（单位：毫秒）
//            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            httpURLConnection.getOutputStream().flush();
            httpURLConnection.getOutputStream().close();
            int code = httpURLConnection.getResponseCode();
            if (code == 200) {
                DataInputStream in = new DataInputStream(httpURLConnection.getInputStream());
                int len = in.available();
                byte[] by = new byte[len];
                in.readFully(by);
                    result = new String(by,"GBK");
                in.close();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result.trim();
    }

    public static void main(String[] args) throws IOException {
        MultipartFile file = getImage("啊啊");
        file.transferTo(new File("C:\\Users\\18745\\Desktop\\index.jpg"));

    }
    public static final String[] colors = {"#673ab7","#009688","#2196f3","#9c27b0"};

    /**
     * 生成纯色图片+字
     * @param username
     * @return
     */
    public static MultipartFile getImage(String username){
//        FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(new Font("宋体", Font.PLAIN, 22));//设计字体
        BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();

        g.setClip(0, 0, 100, 100);//设置绘画的区域,默认背景是黑色，也叫做获取画笔，指定画笔可画的范围
        g.setColor(Color.white);
        g.fillRect(0, 0, 100, 100);//画一个矩形块,颜色是白色，因为画笔颜色是白色
        int i = random.nextInt(3);
        g.setColor(Color.decode(colors[i]));//设置画笔颜色
//        System.out.println(g.getColor().toString());

        g.fillArc(0,0,100,100,0,360);

        g.setColor(Color.white);
        g.setFont(new Font("宋体", Font.PLAIN, 60));
//        System.out.println(g.getFont());
        String s = username.substring(0, 1).toUpperCase();
        int add = 0;
        if(s.charAt(0)>='A'&&s.charAt(0)<='Z')add = 15;
        g.drawString(s,23+add,70);//画字符串

        return new MyImageMultipartFile("header.jpg",image);
    }
    public static String getEmailCode(){
        int i = random.nextInt(1000000);
        StringBuilder s = new StringBuilder(Integer.valueOf(i).toString());
        while (s.length()<6) s.insert(0, '0');
        return s.toString();
    }
    private static class MyImageMultipartFile implements MultipartFile {
        private String originalFilename;
        private BufferedImage image;
        public MyImageMultipartFile(String originalFilename,BufferedImage image){
            this.originalFilename = originalFilename;
            this.image = image;
        }
        @Override
        public String getName() {
            return null;
        }

        @Override
        public String getOriginalFilename() {
            return this.originalFilename;
        }

        @Override
        public String getContentType() {
            return null;
        }

        @Override
        public boolean isEmpty() {
            return false;
        }

        @Override
        public long getSize() {
            return 0;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return null;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return null;
        }

        @Override
        public void transferTo(File dest) throws IOException, IllegalStateException {
            ImageIO.write(image,"jpg",dest);

        }
    }
}
